package cn.growthgate.fgo.factory;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import com.baomidou.mybatisplus.enums.IEnum;

public class EnumConverterFactory implements ConverterFactory<String, IEnum> {

	@SuppressWarnings("rawtypes")
	private static final Map<Class, Converter> converterMap = new HashMap<>();
	
	@Override
	@SuppressWarnings("unchecked")
	public <T extends IEnum> Converter<String, T> getConverter(Class<T> targetType) {
		Converter<String, T> converter = converterMap.get(targetType);
		if (converter == null) {
			converter = new EnumConverter<>(targetType);
			converterMap.put(targetType, converter);
		}
		return converter;
	}
	
	class EnumConverter<T extends IEnum> implements Converter<String, T> {
		
		private Map<String, T> enumMap = new HashMap<>();
		
		public EnumConverter(Class<T> enumType) {
			T[] enums = enumType.getEnumConstants();
			for (T e : enums) {
				enumMap.put(e.getValue().toString(), e);
			}
		}

		@Override
		public T convert(String source) {
			T result = enumMap.get(source);
			if (result == null) {
                throw new IllegalArgumentException("No element matches " + source);
			}
			return result;
		}
		
	}

}
